#include <iostream>
#include <signal.h>

#include "../comm/httplib.h"
#include "oj_control.hpp"
using namespace httplib;
using namespace ns_control;
static Control *ctrl_ptr; // 单例模式
void Recovery(int signo)
{
    ctrl_ptr->RecoveryMachine();
}
int main()
{
    // 信号注册函数,当收到SIGQUIT信号后就执行恢复函数
    signal(SIGQUIT, Recovery);
    // 实例化出一个服务对象
    Server svr;
    // 设置Get Post方法
    Control ctrl;
    ctrl_ptr = &ctrl;
    svr.Get("/all_questions", [&ctrl](const Request &req, Response &resp)
            {
        //返回一张包含所有题目的html网页
        std::string html;
        ctrl.AllQuestions(html);
        resp.set_content(html,"text/html; charset=utf-8"); });
    // 正则表达式(\d+),匹配对应的编号
    svr.Get(R"(/questions/(\d+))", [&ctrl](const Request &req, Response &resp)
            {
        int id=stoi(req.matches[1]);
        std::string html;
        ctrl.Question(id,html);
        resp.set_content(html,"text/html; charset=utf-8"); });
    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp)
             {
        int id=stoi(req.matches[1]);
        std::string request_json=req.body;
        std::string result_json;
        ctrl.Judge(id,request_json,result_json);
        resp.set_content(result_json, "application/json;charset=utf-8"); });
    svr.set_base_dir("./wwwroot");
    // svr.listen("0.0.0.0",8080);  监听ipv4端口,这里我们的服务器的公网ip是ipv6的
    svr.listen("::",8080); // 独立IPv6端口
    return 0;
}